//
//  HZOAuthView.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/19.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import SVProgressHUD

let APP_KEY = "4031619387"
let APP_SECRET = "155beff6a365bef91aef8691975c6e04"
let APP_URL = "http://www.baidu.com/"

class HZOAuthView: UIViewController {
    
    
       
    
    override func loadView() {
        
        //让它的视图 view 是WebView
        view = webView
    }
    
    
    //懒加载 webView
    lazy var webView:UIWebView = {
        
        let webView = UIWebView()
        
        //设置代理
        webView.delegate = self
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(APP_URL)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        return webView
        
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
//        let webView = view as! UIWebView
        
  
        
        //添加导航条的子控件
        setupUI()
        
      
        
    }
    

    
    //添加导航条的子控件
    func setupUI(){
        
        let closeBar = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        let autoFillBar = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
        navigationItem.leftBarButtonItem =  closeBar
        navigationItem.rightBarButtonItem = autoFillBar
        
    }
    
    
    // MARK: -  实现关闭和自动填充按钮事件
    func close(){
        
        //回到上一个界面
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func autoFill(){
        
        print("自动填充")
        
        
        let jsString = "document.getElementById('userId').value='sxsxsx8@126.com';document.getElementById('passwd').value='liu198919'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    

}





// MARK: -  代理的分类
extension HZOAuthView:UIWebViewDelegate{
    
    
    //开始打开网络页面
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show();
        
    }
    
     //结束打开网络页面
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss();
    }
    
    
    //打开网络页面请求时
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request)
        //获取 code
        guard let url = request.URL else{
            print("code 获取失败")
            return false
        }
        
        //如果是用户设置的回调 url 开头的
        if url.absoluteString.hasPrefix(APP_URL) {
            

            
            //获取 url中? 后面的参数,并且判断有没有"code="这个字符串
            if let u = url.query where u.containsString("code="){
                
                //截取 code
                let code = u.substringFromIndex("code=".endIndex)

                
                //获取access_token之后的回调闭包
                HZOAuthVM.sharedVM.giveAccess_token(code, finished: { (succ) -> () in
                    
                    //                    print(succ)
                    if succ == false {
                        print("登录失败")
                        return
                    }
                    
                    
                    //不需要了登录界面,销毁掉
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        
                        //发布通知
                        NSNotificationCenter.defaultCenter().postNotificationName(gotoName, object: nil)
                        
                    })
                    
                  
                    
                    
                })
                
                
            }
            
            return false
        }
        
        
        
         return  true
    }
    
    
      
    
    
}





